package com.ruoyi.resume.service.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.resume.domain.model.*;
import com.ruoyi.resume.domain.model.resumeProfile.*;
import com.ruoyi.resume.domain.response.ResumeAndTagsResp;
import com.ruoyi.resume.domain.response.ResumeMatchResp;
import com.ruoyi.resume.domain.response.SimilarCandidateResp;
import com.ruoyi.resume.mapper.*;
import com.ruoyi.resume.service.AsyncAnalysisResumeService;
import com.ruoyi.resume.service.RadarChartService;
import com.ruoyi.resume.service.ResumeService;
import com.ruoyi.resume.service.TagService;
import com.ruoyi.resume.utils.minIO.MinIOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class ResumeServiceImpl implements ResumeService {

    @Autowired
    private ResumeMapper resumeMapper; // DAO 层，用于访问数据库

    @Autowired
    private TagService tagService; // 注入 TagService

    @Autowired
    private MinIOUtil minIOUtil;

    @Autowired
    private EducationBackgroundMapper educationBackgroundMapper;

    @Autowired
    private WorkExperienceMapper workExperienceMapper;

    @Autowired
    private InternshipExperienceMapper internshipExperienceMapper;

    @Autowired
    private ProjectExperienceMapper projectExperienceMapper;

    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private ResumeRawDataMapper resumeRawDataMapper;
    @Autowired
    private ResumeTagMapper resumeTagMapper;

    @Autowired
    private RadarChartService radarChartService;

    @Autowired
    private AsyncAnalysisResumeService asyncAnalysisResumeService;


    @Override
    public TableDataInfo getResumesByRange(String name,String gender,String nativePlace,String politicalStatus,Integer isOuter, Integer status) {
        // 1. 根据分页参数和筛选条件获取简历信息
        List<BasicInfo> resumes = resumeMapper.selectResumesByDynamicFilter(name,gender,nativePlace,politicalStatus,isOuter, status);


        // 2. 初始化返回结果
        List<ResumeAndTagsResp> responseList = new ArrayList<>();

        // 3. 遍历每条简历信息，调用 TagService 获取对应的标签
        for (BasicInfo basicInfo : resumes) {
            Map<String, Integer> tags = tagService.getTagsByResumeId(basicInfo.getId());

            // 4. 组装简历基本信息和标签信息
            ResumeAndTagsResp resp = new ResumeAndTagsResp();
            resp.setBaseInfo(basicInfo);
            resp.setTags(tags);

            responseList.add(resp);
        }
        TableDataInfo response = new TableDataInfo();
        response.setRows(responseList);
        response.setTotal(new PageInfo<>(resumes).getTotal());
        return response;
    }





    //下载简历，获取简历的下载链接
    @Override
    @Deprecated
    public String downloadResume(int resumeId){
        try{
            String resumePath = resumeId+"/"+resumeId+".pdf";
            return minIOUtil.downloadFileViaLink("resume",resumePath);
        }catch (Exception e){
            return "生成链接失败"+e.getMessage();
        }
    }

    //收藏简历
    @Override
    public int collectResume(int resumeId) {
        // 1. 获取当前登录用户信息
        Long userId = SecurityUtils.getUserId();
        // 2. 插入收藏简历表
        return resumeMapper.insertCollectedResume(userId, resumeId);
    }

    //查询收藏的全部简历
    @Override
    public List<ResumeAndTagsResp> getAllCollectedResumes(String name,String gender,String nativePlace,String politicalStatus) {
        // 1. 获取当前登录用户信息
        Long userId = SecurityUtils.getUserId();
        // 2. 根据用户 ID 查询收藏的简历 ID
        List<Integer> resumeIds = resumeMapper.selectCollectedResumesByUserId(userId);
        // 3. 初始化返回结果
        List<ResumeAndTagsResp> responseList = new ArrayList<>();
        // 4. 遍历每个简历 ID，获取简历基本信息和标签信息
        for (Integer resumeId : resumeIds) {
            BasicInfo basicInfo = resumeMapper.selectResumesByConditions(resumeId,name,gender,nativePlace,politicalStatus);
            if(basicInfo == null){
                continue;
            }
            Map<String, Integer> tags = tagService.getTagsByResumeId(resumeId);
            ResumeAndTagsResp resp = new ResumeAndTagsResp();
            resp.setBaseInfo(basicInfo);
            resp.setTags(tags);
            responseList.add(resp);
        }
        return responseList;
    }

    @Override
    public void deleteCollectedResume(int resumeId) {
        // 1. 获取当前登录用户信息
        Long userId = SecurityUtils.getUserId();
        // 2. 删除收藏的简历
        resumeMapper.deleteCollectedResume(userId, resumeId);
    }

    @Override
    public void updateResumeStatus(int resumeId, int status) {
        // 1. 修改简历的内外部状态
        resumeMapper.updateResumeStatus(resumeId, status);
    }

    @Override
    public SplitResumeResult getResumeContentById(int resumeId) {
        BasicInfo basicInfo = resumeMapper.selectResumeById(resumeId);
        List<EducationBackground> educationBackgrounds = educationBackgroundMapper.selectByResumeId(resumeId);
        List<WorkExperience> workExperiences = workExperienceMapper.selectByResumeId(resumeId);
        List<InternshipExperience> internshipExperiences = internshipExperienceMapper.selectByResumeId(resumeId);
        List<ProjectExperience> projectExperiences = projectExperienceMapper.selectByResumeId(resumeId);

        // 创建并设置实体
        SplitResumeResult splitResumeResult = new SplitResumeResult();
        splitResumeResult.setBasicInfo(basicInfo);
        splitResumeResult.setEducationBackgrounds(educationBackgrounds);
        splitResumeResult.setWorkExperiences(workExperiences);
        splitResumeResult.setInternshipExperiences(internshipExperiences);
        splitResumeResult.setProjectExperiences(projectExperiences);

        // 调用 RadarChartService 一次性生成 dimensions
        Map<String, Integer> dimensions = radarChartService.generateRadarChartDimensions(splitResumeResult);

        // 设置雷达图数据
        RadarChartData radarChartData = new RadarChartData();
        radarChartData.setDimensions(dimensions);
        splitResumeResult.setRadarChartData(radarChartData);
        return splitResumeResult;
    }

    @Override
    public String getResumeFileById(int resumeId) throws Exception {
        String resumePath = resumeId + "/" + resumeId + ".pdf";
        return minIOUtil.downloadFileViaLink("resume", resumePath);
    }

    @Override
    @Transactional
    public void deleteResumeById(int resumeId) throws Exception {
        // 1. 删除简历-简历主表+教育经历+工作经历+实习经历+项目经历+原始简历
        resumeMapper.deleteResumeById(resumeId);
        educationBackgroundMapper.deleteByResumeId(resumeId);
        workExperienceMapper.deleteByResumeId(resumeId);
        internshipExperienceMapper.deleteByResumeId(resumeId);
        projectExperienceMapper.deleteByResumeId(resumeId);
        resumeRawDataMapper.deleteByResumeId(resumeId);
        minIOUtil.deleteFile("resume", resumeId + "/" + resumeId + ".pdf");


        // 2. 删除简历相关的标签
        tagService.deleteTagsByResumeId(resumeId);

        //3. 删除简历相关的收藏信息
        resumeMapper.deleteCollectedResume(SecurityUtils.getUserId(),resumeId);

        //4. 删除简历候选人信息
        jobMapper.deleteJobCandidateByResumeId(resumeId);
    }

    @Override
    public void updateResume(int resumeId, SplitResumeResult resumeDetailsResponse) {
        // 1. 更新简历基本信息
        BasicInfo basicInfo = resumeDetailsResponse.getBasicInfo();
        basicInfo.setId(resumeId);
        resumeMapper.updateResume(basicInfo);

        // 2. 更新教育经历
        List<EducationBackground> educationBackgrounds = resumeDetailsResponse.getEducationBackgrounds();
        educationBackgroundMapper.deleteByResumeId(resumeId);
        resumeMapper.insertEducations(resumeId, educationBackgrounds);

        // 3. 更新工作经历
        List<WorkExperience> workExperiences = resumeDetailsResponse.getWorkExperiences();
        workExperienceMapper.deleteByResumeId(resumeId);
        resumeMapper.insertWorks(resumeId, workExperiences);

        // 4. 更新实习经历
        List<InternshipExperience> internshipExperiences = resumeDetailsResponse.getInternshipExperiences();
        internshipExperienceMapper.deleteByResumeId(resumeId);
        resumeMapper.insertInternships(resumeId, internshipExperiences);

        // 5. 更新项目经历
        List<ProjectExperience> projectExperiences = resumeDetailsResponse.getProjectExperiences();
        projectExperienceMapper.deleteByResumeId(resumeId);
        resumeMapper.insertProjects(resumeId, projectExperiences);

        // 更新ai评价
        asyncAnalysisResumeService.analysisUseAi(String.valueOf(resumeDetailsResponse), resumeId);
    }

    @Override
    public BasicInfo getBasicInfoByResumeId(int resumeId) {
        // 调用 DAO 层方法，从数据库中根据 resumeId 查询 BasicInfo
        return resumeMapper.selectResumeBasicInfoById(resumeId);
    }

    @Override
    public List<SimilarCandidateResp> getSimilarCandidatesByResumeId(int resumeId) {
        // Step 1: 查询目标简历的标签值
        List<String> targetTags = resumeTagMapper.findTagsByResumeId(resumeId);

        if (targetTags == null || targetTags.isEmpty()) {
            return new ArrayList<>(); // 如果没有标签，返回空列表
        }

        // Step 2: 查询与目标简历标签相似的简历及公共标签数量
        List<ResumeMatchResp> similarResumes = resumeTagMapper.findSimilarResumesAndTagCount(targetTags, resumeId);

        // Step 3: 计算匹配度，获取 BasicInfo 和标签列表
        List<SimilarCandidateResp> result = new ArrayList<>();
        for (ResumeMatchResp match : similarResumes) {
            int matchScore = (int) ((match.getCommonTagCount() * 100) / targetTags.size());

            // 调用BasicInfoMapper或其他服务获取 BasicInfo
            BasicInfo basicInfo = getBasicInfoByResumeId(match.getResumeId().intValue());

            // 调用 ResumeMapper 获取标签列表
            List<ResumeTag> tags = resumeTagMapper.selectResumeTagsByResumeId(match.getResumeId().intValue());

            RadarChartData radarChartData = getResumeContentById(basicInfo.getId()).getRadarChartData();

            // 封装结果到 SimilarCandidateResp 对象
            result.add(new SimilarCandidateResp(basicInfo, radarChartData, matchScore, tags));
        }

        return result;
    }

    @Override
    public TableDataInfo getResumesByTags(List<String> tags) {
        // Step 1: 查询与标签匹配的简历ID
        List<Integer> matchingResumeIds = resumeTagMapper.findResumeIdsByTags(tags, tags.size());

        // Step 2: 初始化结果列表

        List<ResumeAndTagsResp> responseList = new ArrayList<>();

        // Step 3: 根据简历ID获取每个简历的基本信息
        for (Integer resumeId : matchingResumeIds) {
            ResumeAndTagsResp resp = new ResumeAndTagsResp();
            BasicInfo basicInfo = resumeMapper.selectResumeBasicInfoById(resumeId);
            Map<String,Integer> resumeTags = tagService.getTagsByResumeId(resumeId);
            if (basicInfo != null && resumeTags!= null ) {
                resp.setBaseInfo(basicInfo);
                resp.setTags(resumeTags);
            }
            responseList.add(resp);
        }
        TableDataInfo result = new TableDataInfo();
        result.setRows(responseList);
        result.setTotal(new PageInfo<>(matchingResumeIds).getTotal());
        return result; // 返回符合条件的简历列表
    }

    /**
     * 获取最新的简历动态
     * */
    @Override
    public List<ResumeAndTagsResp> getLatestResumes() {
        // 1. 查询最新的10条简历
        List<BasicInfo> latestResumes = resumeMapper.selectLatestResumes();
        // 2.获取简历的标签
        List<ResumeAndTagsResp> responseList = new ArrayList<>();
        for (BasicInfo basicInfo : latestResumes) {
            Map<String, Integer> tags = tagService.getTagsByResumeId(basicInfo.getId());
            ResumeAndTagsResp resp = new ResumeAndTagsResp();
            resp.setBaseInfo(basicInfo);
            resp.setTags(tags);
            responseList.add(resp);
        }
        return responseList;
    }

    /**
     * 获取人才地图
     * */
    @Override
    public List<Mappings> getTalentMap() {
        List<Mappings> mappingsList = new ArrayList<>();

        //1.查询所有简历的公司-部门-姓名-职位信息
        List<WorkExperiencePlus> workExperiences= workExperienceMapper.selectCompanyInfo();

        //2.根据公司名称分组
        Map<String, List<WorkExperiencePlus>> companyMap = new HashMap<>();
        for (WorkExperiencePlus workExperience : workExperiences) {
            String companyName = workExperience.getCompanyName();
            companyMap.computeIfAbsent(companyName, k -> new ArrayList<>()).add(workExperience);
        }

        //3.遍历公司名称，构建人才地图
        for (Map.Entry<String, List<WorkExperiencePlus>> entry : companyMap.entrySet()) {
            String companyName = entry.getKey();
            List<WorkExperiencePlus> workExperienceList = entry.getValue();
            List<Map<String, List<People>>> mappingList = new ArrayList<>();
            Map<String, List<People>> departmentMap = new HashMap<>();
            for (WorkExperiencePlus workExperience : workExperienceList) {
                String departmentName = workExperience.getDepartment();
                String jobTitle = workExperience.getJobTitle();
                // 获取姓名
                //String name = workExperienceMapper.getNameByResumeId(workExperience.getResumeId());太耗时
                String name = workExperience.getName();
                People people = new People(name, jobTitle, workExperience.getStartTime(), workExperience.getEndTime());
                departmentMap.computeIfAbsent(departmentName, k -> new ArrayList<>()).add(people);
            }
            // 将部门名称和对应的人员列表添加到映射中
            mappingList.add(departmentMap);
            // 将公司名称和映射列表添加到人才地图中
            mappingsList.add(new Mappings(companyName, mappingList));
        }

        return mappingsList;
    }


}
